package com.spzx.cart.service.impl;

import com.spzx.cart.api.domain.CartInfo;
import com.spzx.cart.service.CartInfoService;
import com.spzx.common.core.constant.SecurityConstants;
import com.spzx.common.core.context.SecurityContextHolder;
import com.spzx.common.core.domain.R;
import com.spzx.common.core.exception.ServiceException;
import com.spzx.product.api.RemoteProductService;
import com.spzx.product.api.model.ProductSku;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * @author: atguigu
 * @create: 2025-05-07 15:51
 */
@Service
public class CartInfoServiceImpl implements CartInfoService {

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private RemoteProductService remoteProductService;

    /**
     * 将指定商品ID对应数量加入到购物车
     *
     * @param skuId
     * @param num
     */
    @Override
    public void addToCart(Long skuId, Integer num) {
        //1. 判断购物车中是否有该商品
        Long userId = SecurityContextHolder.getUserId();
        String cartKey = this.getCartKey(userId);
        String field = skuId.toString();
        //写法一
        //Boolean exists = redisTemplate.opsForHash().hasKey(cartKey, field);
        //写法二：创建BoundHashOperations对象
        BoundHashOperations<String, String, CartInfo> hashOps = redisTemplate.boundHashOps(cartKey);
        Boolean exists = hashOps.hasKey(field);
        //2. 如果商品存在，则更新数量 单品数量上限99
        if (exists) {
            CartInfo cartInfo = (CartInfo) redisTemplate.opsForHash().get(cartKey, field);
            Integer skuNum = cartInfo.getSkuNum();
            cartInfo.setSkuNum(skuNum + num > 99 ? 99 : skuNum + num);
            cartInfo.setUpdateTime(new Date());
            //redisTemplate.opsForHash().put(cartKey, field, cartInfo);
            hashOps.put(field, cartInfo);
        } else {
            //3.如果商品不存在，则构建购物车商品对象，限制最多加购商品数量50个，并保存到购物车中
            //3.1 业务校验
            //Long count = redisTemplate.opsForHash().size(cartKey);
            Long count = hashOps.size();
            if (count > 50) {
                throw new RuntimeException("最多只能加入50个商品");
            }
            //3.2 远程调用商品服务获取商品信息
            R<ProductSku> r = remoteProductService.getProductSku(skuId, SecurityConstants.INNER);
            if (r.getCode() != 200) {
                throw new ServiceException("远程调用商品服务失败，原因：" + r.getMsg());
            }
            ProductSku productSku = r.getData();
            //3.3 构建购物车商品对象
            CartInfo cartInfo = new CartInfo();
            cartInfo.setUserId(userId);
            cartInfo.setSkuId(productSku.getId());
            cartInfo.setCartPrice(productSku.getSalePrice());
            cartInfo.setSkuPrice(productSku.getSalePrice());
            cartInfo.setSkuNum(num > 99 ? 99 : num);
            cartInfo.setThumbImg(productSku.getThumbImg());
            cartInfo.setSkuName(productSku.getSkuName());
            cartInfo.setIsChecked(1);
            //3.4 将购物车商品写入Redis
            //redisTemplate.opsForHash().put(cartKey, field, cartInfo);
            hashOps.put(field, cartInfo);
        }
    }


    private String getCartKey(Long userId) {
        //定义key user:userId:cart
        return "user:cart:" + userId;
    }
}
